package com.mhs.controller;


import com.mhs.entity.Article;
import com.mhs.service.IArticleService;
import com.mhs.utils.RedisCache;
import com.mhs.vo.ArticleVo;
import com.mhs.vo.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.system.ApplicationHome;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author Fantasy0521
 * @since 2023-04-09
 */
@RestController
@RequestMapping("/mhs/article")
@RefreshScope // 开启nacos配置热更新
public class ArticleController {


    @Value("${linuxImg.url}")
    private String url;

    @Resource
    private RedisCache redisCache;
    
    //文件上传 上传图片
    @PostMapping("upload")
    public Result upload(MultipartFile file) {
//        System.out.println(file);
        //获取文件原始名,使用原始名可能出现覆盖问题
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //这里采取随机生成一个文件名
        //使用UUID重新生成文件名
        String fileName = UUID.randomUUID().toString() + suffix;

//        String basePath = getSavePath();
        String basePath = url;

        //创建一个目录对象
        File dir = new File(basePath);
        //判断当前目录是否存在
        if (!dir.exists()) {
            //目录不存在,创建
            dir.mkdir();
        }

        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            //e.printStackTrace();
        }

        return Result.success("上传成功", fileName);

    }


    
    
    /**
     * 文件下载
     *
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {

//            String basePath = getSavePath();
            String basePath = url;

            //输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            //输出流,通过输出流将文件同时写会浏览器,在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("images/jepg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            //e.printStackTrace();
        }


    }

    /**
     * 保存文件的路径
     *
     * @return path
     */
    public String getSavePath() {
        // 这里需要注意的是ApplicationHome是属于SpringBoot的类
        // 获取项目下resources/static/img路径
        ApplicationHome applicationHome = new ApplicationHome(this.getClass());

        // 保存目录位置根据项目需求可随意更改
        return applicationHome.getDir().getParentFile()
                .getParentFile().getAbsolutePath() + "/src/main/resources/static/img/";
    }

    @Resource
    private IArticleService articleService;
    
    /**
     * 发布咨询帖
     * @param article
     * @return
     */
    @PostMapping("send")
    public Result send(@RequestBody ArticleVo article){
        return articleService.send(article);
    }

    /**
     * 分页查询文章列表
     * @return
     */
    @GetMapping("list")
    public Result list(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "20") Integer pageSize){
        return articleService.getArticleListByPage(page,pageSize);
    }

    /**
     * 根据文章Id查询文章以及作者的信息
     * @param articleId
     * @return
     */
    @GetMapping("getArticleById")
    public Result getArticleById(Integer articleId){
        return articleService.getArticleById(articleId);
    }

    /**
     * 点赞
     * @return
     */
    @GetMapping("pick")
    public Result pick(Integer articleId){
        return articleService.pick(articleId);
    }

    @PutMapping
    public Result editArticle(@RequestBody ArticleVo articleVo){
        articleService.updateById(articleVo);
        redisCache.deleteObject("articlePage");
        return Result.success("修改成功");
    }
    @DeleteMapping
    public Result deleteArticle(@RequestBody ArticleVo articleVo){
        articleService.removeById(articleVo);
        redisCache.deleteObject("articlePage");
        return Result.success("删除成功");
    }

    
}

